package tribe.vilt.lost.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;
import tribe.vilt.lost.activity.PlayAudioActivity;

/**
 * Created by Tobias Ericsson
 */
public class SMSReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        //To change body of implemented methods use File | Settings | File Templates.
        //---get the SMS message passed in---
        Bundle bundle = intent.getExtras();
        SmsMessage[] msgs = null;
        String message = "";
        if (bundle != null) {
            //---retrieve the SMS message received---
            Object[] pdus = (Object[]) bundle.get("pdus");
            msgs = new SmsMessage[pdus.length];
            for (int i = 0; i < msgs.length; i++) {
                msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
                message += "SMS from " + msgs[i].getOriginatingAddress();
                message += " :";
                message += msgs[i].getMessageBody();
                message += "\n";
            }
            //---display the new SMS message---
            Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
        }

        if (message.toLowerCase().startsWith("@locate")) {

            Intent playAudioIntent = new Intent(context, PlayAudioActivity.class);
            context.startActivity(playAudioIntent);
            playAudioIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            playAudioIntent.putExtra("message", message);
            abortBroadcast();
        }
    }
}

